import 'package:flutter/material.dart';

class CommonDialog {
  
   /* 
    IntrinsicWidth：让父组件宽度根据子组件的固有宽度调整。
    IntrinsicHeight：让父组件高度根据子组件的固有高度调整。
    尽量不要频繁使用  会多次测量子组件的尺寸，从而影响性能
  */
  // 显示自定义对话框

  /// showCustomDialog 完全自定义弹框 
  static Future<bool?> showCustomDialog({
    required BuildContext context,
    String? title,
    required Widget content,
    required String confirmText,
    bool showCloseIcon = true,
    bool maskClick = false,
    // Color confirmTextColor = Colors.black,
    String? cancelText,
    // Color cancelTextColor = Colors.blue,
    double borderRadius = 16.0,
    VoidCallback? onClose,
    VoidCallback? onCancel,
  }) {
    // 动态获取主题的按钮颜色 最终考虑的解决方向是 封装全局的 appTextButtons 对亮色和暗色做区别
    // final confirmTextColor = Theme.of(context).colorScheme.onPrimary;
    // final cancelTextColor = Theme.of(context).colorScheme.primary;

    return showGeneralDialog<bool>(
      context: context,
      barrierDismissible: maskClick,
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
      barrierColor: Colors.black.withOpacity(0.4),
      transitionDuration: const Duration(milliseconds: 240),
      pageBuilder: (context, animation, secondaryAnimation) {
        return Align(
          alignment: Alignment.bottomCenter,
          child: Material(
            color: Colors.transparent,
            child: Dialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(borderRadius),
              ),
              child: Container(
                width: MediaQuery.of(context).size.width * 0.9,
                constraints: BoxConstraints(
                  maxHeight: MediaQuery.of(context).size.height * 0.8,
                ),
                child: Stack(
                  children: [
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        if (title != null && title.isNotEmpty)
                          Padding(
                            padding: const EdgeInsets.only(
                              left: 16.0,
                              right: 16.0,
                              top: 24.0,
                            ),
                            child: Text(
                              title,
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                              textAlign: TextAlign.center,
                            ),
                          ),
                        Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16.0,
                            vertical: 24.0,
                          ),
                          child: content,
                        ),
                        _buildButtons(
                          context: context,
                          confirmText: confirmText,
                          // confirmTextColor: confirmTextColor,
                          cancelText: cancelText,
                          // cancelTextColor: cancelTextColor,
                          onCancel: onCancel,
                        ),
                      ],
                    ),
                    if (showCloseIcon)
                      Positioned(
                        top: 0,
                        right: 0,
                        child: Material(
                          color: Colors.transparent,
                          child: IconButton(
                            icon: const Icon(Icons.close, color: Colors.black),
                            onPressed: () {
                              if (onClose != null) {
                                Navigator.of(context).pop();
                                onClose();
                              } else {
                                Navigator.of(context).pop(false);
                              }
                            },
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
      transitionBuilder: (context, animation, secondaryAnimation, child) {
        // 淡入淡出动画
        final fadeAnimation = CurvedAnimation(
          parent: animation,
          curve: Curves.easeInOut, // 淡入淡出的缓动曲线
        );
        // 缩放动画
        final scaleAnimation = Tween<double>(
          begin: 0.7, // 初始缩小
          end: 1.0, // 最终正常大小
        ).animate(CurvedAnimation(
          parent: animation,
          curve: Curves.easeOutCubic, // 缓动曲线
        ));
        return FadeTransition(
          opacity: fadeAnimation,
          child: ScaleTransition(scale: scaleAnimation , child: child,),
        );
      },
    );
  }

  static Widget _buildButtons({
    required BuildContext context,
    required String confirmText,
    // required Color confirmTextColor,
    String? cancelText,
    // required Color cancelTextColor,
    VoidCallback? onCancel,
  }) {
    if (cancelText == null) {
      // 单按钮布局
      return Container(
        decoration: const BoxDecoration(
          border: Border(
            top: BorderSide(color: Color(0xFFCCCCCC), width: 1),
          ),
        ),
        child: TextButton(
          onPressed: () {
            Navigator.of(context).pop(true);
          },
          child: Text(
            confirmText,
            style: const TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              // color: confirmTextColor,
            ),
          ),
        ),
      );
    }

    // 双按钮布局
    return Container(
      decoration: const BoxDecoration(
        border: Border(
          top: BorderSide(color: Color(0xFFCCCCCC), width: 1),
        ),
      ),
      child: Row(
        children: [
          Expanded(
            child: TextButton(
              onPressed: () {
                Navigator.of(context).pop(true);
              },
              child: Text(
                confirmText,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  // color: confirmTextColor,
                ),
              ),
            ),
          ),
          Container(
            width: 0.5, // 分割线宽度
            height: 48,
            color: const Color(0xFFCCCCCC), // 分割线颜色
          ),
          Expanded(
            child: TextButton(
              onPressed: () {
                if (onCancel != null) {
                  Navigator.of(context).pop();
                  onCancel();
                } else {
                  Navigator.of(context).pop(false);
                }
              },
              child: Text(
                cancelText,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 显示加载框  同步异步的警告和遮盖层覆盖全屏无法解决 使用 overlay 解决封装
  static Future<void> showLoadingDialog({
    required BuildContext context,
    double iconSize = 48.0, // 默认加载图标大小
    double padding = 24.0,  // 默认遮罩层的 padding
  }) async {
    showDialog<void>(
      context: context,
      barrierDismissible: false, // 禁止点击外部关闭
      builder: (BuildContext context) {
        return UnconstrainedBox(
          child: Container(
            padding: EdgeInsets.all(padding),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12.0), // 圆角
            ),
            child: SizedBox(
              width: iconSize,
              height: iconSize,
              child: const CircularProgressIndicator(strokeWidth: 3.0),
            ),
          ),
        );
      },
    );
  }
  // 隐藏加载框
  static void hideLoadingDialog(BuildContext context) {
    if (Navigator.of(context, rootNavigator: true).canPop()) {
      Navigator.of(context, rootNavigator: true).pop();
    }
  }
  // 包装异步任务的方法
  static Future<void> runWithLoadingDialog<T>({
    required BuildContext context,
    required Future<T> Function() asyncTask, // 异步任务
    double iconSize = 48.0,
    double padding = 24.0,
  }) async {
    bool mounted = true;
    // 显示加载框
    showLoadingDialog(context: context, iconSize: iconSize, padding: padding);
    try {
      // 执行异步任务
      await asyncTask();
    } finally {
      // 确保在加载框关闭前检查 `mounted` 状态
      if (mounted) {
        // ignore: use_build_context_synchronously
        hideLoadingDialog(context);
      }
    }
  }
 
  static Future<void> showInfoDialog( BuildContext context, String message) async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // 禁止点击外部关闭
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('提示'),
          content: Text(message),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  static Future<bool?> showConfirmDialog( BuildContext context, String message) async {
    return showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认操作'),
          content: Text(message),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(false); // 取消
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(true); // 确认
              },
              child: const Text('确认'),
            ),
          ],
        );
      },
    ); // 返回默认值 false
  }

}



 /* 
transitionBuilder: (context, animation, secondaryAnimation, child) {
  // 淡入淡出动画
  final fadeAnimation = CurvedAnimation(
    parent: animation,
    curve: Curves.easeInOut, // 淡入淡出的缓动曲线
  );
  // 缩放动画
  final scaleAnimation = Tween<double>(
    begin: 0.8, // 初始缩小
    end: 1.0, // 最终正常大小
  ).animate(CurvedAnimation(
    parent: animation,
    curve: Curves.easeOutCubic, // 缓动曲线
  ));
  // 滑动动画
  final offsetAnimation = Tween<Offset>(
    begin: const Offset(0, 1), // 初始位置在屏幕底部
    end: Offset.zero, // 最终位置
  ).animate(CurvedAnimation(
    parent: animation,
    curve: Curves.easeOutCubic,
  ));
  return FadeTransition(
    opacity: fadeAnimation,
    child: ScaleTransition(
      scale: scaleAnimation,
      child: SlideTransition(
        position: offsetAnimation,
        child: child,
      ),
    ),
  );
},
*/